//
//  UserModifyViewController.m
//  Wujin
//
//  Created by cz on 2016/12/12.
//  Copyright © 2016年 dong. All rights reserved.
//

#import "UserModifyViewController.h"

@interface UserModifyViewController ()<UITextFieldDelegate>

@property (weak, nonatomic) IBOutlet UITextField *oldPassword;
@property (weak, nonatomic) IBOutlet UITextField *password;
@property (weak, nonatomic) IBOutlet UITextField *repeatPassword;

@end

@implementation UserModifyViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //给个返回按钮
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStylePlain target:self action:@selector(goback)];
    
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    
    [self.view endEditing:YES];
    
}

- (IBAction)goback {
    [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)modifyPassword {
    
    if (self.oldPassword.text.length == 0 || self.password.text.length == 0 || self.repeatPassword.text.length == 0) {
        
        [MRHud showWithFailure:@"输入不能为空"];
        return;
    }
    if (self.oldPassword.text == self.password.text) {
        [MRHud showWithFailure:@"新密码不能与旧密码相同"];
        return;
    }
    
    if (self.password.text != self.repeatPassword.text) {
        [MRHud showWithFailure:@"两次输入不一致"];
        return;
    }
    
    
    NSString *url = F(@"%@User/editPassword", BASEURL);
    
    NSDictionary *pwdInfo = @{
                               @"password":self.password.text,
                               @"oldPassword":self.oldPassword.text,
                               @"user_id":[WJUser user].user_id
                               };
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:pwdInfo options:NSJSONWritingPrettyPrinted error:nil];
    NSString *jsonStr = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
    NSDictionary *dict = @{
                           @"data":jsonStr
                           };
    
    [FSServer requestWithTarget:url param:dict result:^(id responseObject, NSError *error) {
        if ([responseObject isKindOfClass:[NSDictionary class]])
        {
            if ([responseObject[@"flag"] intValue] == 1) {
                
                NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
                [defaults setObject:self.password.text forKey:@"Password"];
                [MRHud showWithSuccess:@"修改成功，下次请用新密码登录" afterDelay:1.0];
                [self goback];
                
            }else{
                [MRHud showWithFailure:@"修改失败，请重新修改"];
            }
            
        }
    }];
}

@end
